package com.lingkang.top.seesister.activity.home.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lingkang.top.seesister.R;
import com.lingkang.top.seesister.config.UrlConfig;
import com.lingkang.top.seesister.entity.TabEntity;
import com.lingkang.top.seesister.network.OkHttpRequest;
import com.lingkang.top.seesister.utils.GlideUtils;
import com.lingkang.top.seesister.utils.SharedPreferencesUtils;
import com.lingkang.top.seesister.utils.ViewFindUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import es.dmoral.toasty.Toasty;
import me.panpf.sketch.SketchImageView;

public class ErCiYuanFragment extends Fragment {


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getActivity()).inflate(R.layout.home_erciyuan_fragment, container, false);
    }

    private SketchImageView imageView;
    private CommonTabLayout mTabLayout_4;
    private View mDecorView;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String[] mTitles = {"二次元", "美女(慎入)", "其他"};
    private SwipeRefreshLayout srlErciyuan;
    private Button btnTop, btnLower;
    private TextView tvAlt;
    private TextView tvNo;
    private int no = 0;
    private boolean ageFull18 = false;
    //请求最新图片url
    private String newPictureUrl = null;
    private String alt = null;
    private int thisIndex = 0;


    @Override
    public void onStart() {
        super.onStart();

        imageView = getActivity().findViewById(R.id.my_image);
        imageView.setZoomEnabled(true);
        imageView.setShowDownloadProgressEnabled(true);
        btnLower = getActivity().findViewById(R.id.btn_lower);
        btnTop = getActivity().findViewById(R.id.btn_top);
        tvAlt = getActivity().findViewById(R.id.tv_alt);
        tvNo = getActivity().findViewById(R.id.tv_no);

        //加载图片
        initImages();
        //初始化页眉tab
        initHeaderTab();

        newPictureUrl = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=333854384,36116664&fm=26&gp=0.jpg";

        GlideUtils.callBack(getContext(), newPictureUrl, imageView, new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                Toasty.warning(getContext(), "服务器开了小差~", Toast.LENGTH_SHORT, true).show();
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                return false;
            }
        });

        //图片缩放等设置
        seeAndSavePicture();
    }

    private void initImages() {
        //当前阅读到的页
        no = (int) SharedPreferencesUtils.get().get(getContext(), "meinv_now_no", 0);

        //上一张
        btnTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (no < 1) {
                    return;
                }
                if (thisIndex == 1)
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            no--;
                            SharedPreferencesUtils.get().put(getContext(), "meinv_now_no", no);
                            String url = UrlConfig.Ip + UrlConfig.getNowPicture + "?type=性感美女&no=" + no;
                            String result = OkHttpRequest.get(url);
                            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
                            newPictureUrl = jsonObject.get("data").getAsJsonObject().get("url").toString();
                            alt = jsonObject.get("data").getAsJsonObject().get("alt").toString();
                            newPictureUrl = newPictureUrl.replaceAll("\"", "");
                            updateMeiNv.sendEmptyMessage(1);
                        }
                    }).start();
            }
        });

        //下一章
        btnLower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (thisIndex == 1)
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            no++;
                            SharedPreferencesUtils.get().put(getContext(), "meinv_now_no", no);
                            String url = UrlConfig.Ip + UrlConfig.getNowPicture + "?type=性感美女&no=" + no;
                            String result = OkHttpRequest.get(url);
                            JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
                            newPictureUrl = jsonObject.get("data").getAsJsonObject().get("url").toString();
                            newPictureUrl = newPictureUrl.replaceAll("\"", "");
                            alt = jsonObject.get("data").getAsJsonObject().get("alt").toString();
                            updateMeiNv.sendEmptyMessage(1);
                        }
                    }).start();
            }
        });


        srlErciyuan = getActivity().findViewById(R.id.srl_erciyuan);
    }

    private void initHeaderTab() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], 0, 0));
        }
        mDecorView = getActivity().getWindow().getDecorView();
        /** indicator固定宽度 */
        mTabLayout_4 = ViewFindUtils.find(mDecorView, R.id.header_tab);
        mTabLayout_4.setTabData(mTabEntities);
        mTabLayout_4.setCurrentTab(0);
        mTabLayout_4.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                thisIndex = position;
                if (position == 0) {
                    mTabLayout_4.setCurrentTab(0);
                    tvAlt.setText("");
                    tvNo.setText("");
                    newPictureUrl = "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=333854384,36116664&fm=26&gp=0.jpg";
                    GlideUtils.callBack(getContext(), newPictureUrl, imageView, new RequestListener() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                            Toasty.warning(getContext(), "服务器开了小差~", Toast.LENGTH_SHORT, true).show();
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    });
                } else if (position == 1) {
                    if (!ageFull18)
                        new XPopup.Builder(getContext()).asConfirm("警告", "未满18岁慎入，图片来源：http://mzitu.com 请在24小时后删除",
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        mTabLayout_4.setCurrentTab(1);
                                        ageFull18 = true;
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                String url = UrlConfig.Ip + UrlConfig.getNowPicture + "?type=性感美女&no=" + no;
                                                String result = OkHttpRequest.get(url);
                                                JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
                                                newPictureUrl = jsonObject.get("data").getAsJsonObject().get("url").toString();
                                                newPictureUrl = newPictureUrl.replaceAll("\"", "");
                                                alt = jsonObject.get("data").getAsJsonObject().get("alt").toString();
                                                updateMeiNv.sendEmptyMessage(1);
                                            }
                                        }).start();
                                    }
                                }).show();
                    //未满18不能进入
                    if (ageFull18) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String url = UrlConfig.Ip + UrlConfig.getNowPicture + "?type=性感美女&no=" + no;
                                String result = OkHttpRequest.get(url);
                                JsonObject jsonObject = (JsonObject) new JsonParser().parse(result);
                                newPictureUrl = jsonObject.get("data").getAsJsonObject().get("url").toString();
                                newPictureUrl = newPictureUrl.replaceAll("\"", "");
                                alt = jsonObject.get("data").getAsJsonObject().get("alt").toString();
                                updateMeiNv.sendEmptyMessage(1);
                            }
                        }).start();
                    } else
                        mTabLayout_4.setCurrentTab(0);
                } else if (position == 2) {
                    mTabLayout_4.setCurrentTab(2);
                    tvAlt.setText("");
                    tvNo.setText("");
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private void seeAndSavePicture() {
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                new XPopup.Builder(getContext()).asConfirm("信息", "保存图片",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                // 首先保存图片 创建文件夹
                                File appDir = new File(Environment.getExternalStorageDirectory(), "image");
                                if (!appDir.exists()) {
                                    appDir.mkdir();
                                }
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                                String name = newPictureUrl.substring(newPictureUrl.length() - 4);
                                //图片文件名称
                                String fileName = simpleDateFormat.format(new Date()) + name;
                                File file = new File(appDir, fileName);
                                try {
                                    FileOutputStream fos = new FileOutputStream(file);
                                    Bitmap bitmap = ((BitmapDrawable) (imageView).getDrawable()).getBitmap();
                                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                                    fos.flush();
                                    fos.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                // 其次把文件插入到系统图库
                                String path = file.getAbsolutePath();
                                try {
                                    MediaStore.Images.Media.insertImage(getContext().getContentResolver(), path, fileName, null);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                                // 最后通知图库更新
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                Uri uri = Uri.fromFile(file);
                                intent.setData(uri);
                                getContext().sendBroadcast(intent);
                                Toasty.success(getContext(), "保存成功！", Toast.LENGTH_SHORT, true).show();
                            }
                        }).show();
                return false;
            }
        });
    }

    private Handler updateMeiNv = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //更新
            if (msg.what == 1) {
                GlideUrl cookie = new GlideUrl(newPictureUrl, new LazyHeaders.Builder().addHeader("Referer", "https://www.mzitu.com/").build());
                Glide.with(getContext())
                        .load(cookie)
                        .into(imageView);
                tvAlt.setText(alt);
                tvNo.setText(String.valueOf(no));
            }
        }
    };
}
